package Servelts;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import daoFactory.DaoFactory;
import daoImpls.GoodDAOImpl;
import daoImpls.OrderDAOImpl;
import daoImpls.UserDAOImpl;
import vo.Good;
import vo.Order;
import vo.User;
@WebServlet("/listOrderItem")
public class OrderItemListServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String status = request.getParameter("status");
		String url = "error.jsp";
		//查询购物车
		if(status.equals("selectall")){
			int start=request.getParameter("start")==null?0:Integer.parseInt(request.getParameter("start"));
		    int pageSize = 4;
		    List<Order> ois = (List<Order>) request.getSession().getAttribute("ois");
		    int total = ois == null?0:ois.size();
		    int totalPage = total % pageSize > 0 ? total / pageSize + 1 : total / pageSize;
		    int prePage = start-1;
		    if(prePage<0) prePage = 0;
		    int nextPage = start+1;
		    if(nextPage+1>totalPage) nextPage = totalPage-1;
		       
		    request.setAttribute("totalPage", totalPage);
		    request.setAttribute("prePage", prePage); 
		    request.setAttribute("nextPage", nextPage);
		    List<Order> news = sublist(ois, start, pageSize);
		    request.getSession().setAttribute("orderitem", news);
		    int size = news==null?0:news.size();
		    int totalsize = ois==null?0:ois.size();
		    request.getSession().setAttribute("size", size);
	        request.setAttribute("totalsize", totalsize);
	        request.setAttribute("uid", request.getSession().getAttribute("userid"));
	        if(ois!=null) request.setAttribute("sum", sumOrderItem(ois));
	        
//			url = "listOrderItem.jsp";
			url = "shopCar.jsp";
		}
		//商品添加购物车
		if(status.equals("add")){
			String uid = (String) request.getSession().getAttribute("userid");
			int num = Integer.parseInt(request.getParameter("num"));
			String gid = request.getParameter("gid");
			Order order = new Order();
			order.setGood(DaoFactory.getGoodFactory().get(gid));
			order.setoNum(num);
			order.setUser(DaoFactory.getUserFactory().get(uid));
			List<Order> ois = (List<Order>) request.getSession().getAttribute("ois");
		       if (null == ois) {
		           ois = new ArrayList<Order>();
		           request.getSession().setAttribute("ois", ois);
		        }
		       boolean found = false;
		       for(Order v:ois){
		    	   if(v.getGood().getGid().equals(order.getGood().getGid())){
		    		   v.setoNum(v.getoNum()+order.getoNum());
		    		   found = true;
		    		   break;
		    	   }
		       }
		       if(!found) ois.add(order);
		       url = "listOrderItem?status=selectall";
		}
		//修改
		if(status.equals("update")){
			 List<Order> ois = (List<Order>) request.getSession().getAttribute("ois");
			 String num = request.getParameter("num");
			 Order order;
			 for (int i = 0; i <ois.size(); i++) {
				 if(ois.get(i).getGood().getGid().equals(request.getParameter("oid"))){
					 order = ois.get(i);
					 if(num.equals("add")){
						 int oNum =order.getoNum();
						 oNum++;
						 if(oNum>order.getGood().getGnum()) break;
						 order.setoNum(oNum);  
					 }
					 if(num.equals("red")){
						 int oNum =order.getoNum();
						 oNum--;
						 if(oNum<=0) break;
						 order.setoNum(oNum);
					 }
					 ois.set(i, order);
				 }
			}
			 request.getSession().setAttribute("ois", ois);
			 url = "listOrderItem?status=selectall";
		}
		
		
		//删除
		if(status.equals("delete")){
			String id = request.getParameter("id");
	        List<Order> ois = (List<Order>) request.getSession().getAttribute("ois");
	       
	        for (int i = ois.size()-1;i>=0;i--) {
	        	if (ois.get(i).getGood().getGid().equals(id)) {
					ois.remove(ois.get(i));
					request.getSession().setAttribute("ois", ois);
	        	}
			}
	        url = "listOrderItem?status=selectall";
		}
		//范围删除
		if(status.equals("deletequery")){
			String[] ids = request.getParameter("ids").split(",");
			List<Order> ois = (List<Order>) request.getSession().getAttribute("ois");
			
			for(int j=0;j<ids.length;j++){
				for (int i = ois.size()-1;i>=0;i--) {
		        	if (ois.get(i).getGood().getGid().equals(ids[i])) {
						ois.remove(ois.get(i));
						request.getSession().setAttribute("ois", ois);
		        	}
				}
			}
			
			url = "listOrderItem?status=selectall";
		}
		//提交
		if(status.equals("submit")){
			 List<Order> ois = (List<Order>) request.getSession().getAttribute("ois");
				//添加
				try{
					String uid = (String) request.getSession().getAttribute("userid");
					User user = DaoFactory.getUserFactory().get(uid);
					Good good;
					double balance = user.getBalance();
					double money;
					int num;
					int gnum;
					for (int i = 0; i < ois.size(); i++) {
						gnum =ois.get(i).getGood().getGnum();
						money = ois.get(i).getGood().getgPrice()*ois.get(i).getoNum();
						num = ois.get(i).getoNum() ;
						if(money<=balance&&num<=gnum){
							DaoFactory.getOrderFactory().add(ois.get(i));
							balance -= money;
							gnum -= num;
							good = ois.get(i).getGood();
							good.setGnum(gnum);
							DaoFactory.getGoodFactory().update(good);
							user.setBalance(balance);
							DaoFactory.getUserFactory().update(user);
							
							System.out.println("订单添加操作成功");
							request.getSession().removeAttribute("ois");
						}else{
							response.getWriter().println("<script type='text/javascript'>  alert('余额不足'); location.href='listOrderItem?status=selectall'; </script>");
							return;
						}
					}
					
				}catch(Exception e){
					System.out.println("订单添加操作错误:" + e.getMessage());
				}
				url = "jump?status=index";
		}
		
		
		
		request.getRequestDispatcher(url).forward(request, response);
	}
	
	private List<Order> sublist(List<Order> list,int start,int end){
		List<Order> news = new ArrayList<>();
		if(start >end|| end ==0) return null;
		int total = list == null?0:list.size();
		for (int i = start; i <end; i++) {
			if (i<total){
				news.add(list.get(i));
			}
		}
		return news;
	}
	private double sumOrderItem(List<Order> list){
		double sum = 0;
		Good good;
		int num = 0;
		for(Order v:list){
			good = v.getGood();
			num = v.getoNum();
			sum += good.getgPrice()*num;
		}
		
		return sum;
	}
	
}
